package com.building.hcrm.ui.customer;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.CallLog.Calls;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.building.hcrm.R;
import com.building.hcrm.R.array;
import com.building.hcrm.R.id;
import com.building.hcrm.R.layout;
import com.building.hcrm.R.string;
import com.building.hcrm.base.BaseActivity;
import com.building.hcrm.common.ComConst;
import com.building.hcrm.common.ComFunc;
import com.building.hcrm.common.User;
import com.building.hcrm.model.CallLog;
import com.building.hcrm.model.CustomerDetail;
import com.building.hcrm.model.CustomerQuery;
import com.building.hcrm.wcf.CustomerServiceProxy;

/**
 * 客户资料填写界面
 * 
 * @author hby
 * 
 */
public class CustomerEditActivity extends BaseActivity {

	private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	// 基本信息
	private EditText etName;
	private EditText etPhone;
	private EditText etMail;
	private AutoCompleteTextView actvMailType;
	private TextView tvJob;
	private TextView tvInvestment;
	private EditText etAge;
	private RadioButton rbtnMale;
	private RadioButton rbtnFemale;

	private EditText etAddress;

	// 其他信息
	private TextView tvClassify;
	private TextView tvFollow;
	private TextView tvBelong;
	private TextView tvRemark;
	private TextView tvRecord;
	private TextView tvRecourse;
	private ImageButton igmBtnSave;

	private ImageButton imgbtnSendMsg;
	private ImageButton imgbtnCallPhone;

	private List<String> jobStrings;
	private List<String> recourseStrings;

	ArrayAdapter<String> av;

	private CustomerDetail mCustomerDetail;
	private CustomerQuery mCustomerQuery;

	private boolean addFlags;
	private int mActivityStatus = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_customer_edit);
		initControls();
		initDatas();
		setOnAllListeners();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			finish();
			slideReturnActivity();
		}
		return false;
	}

	private void initControls() {
		etName = (EditText) findViewById(id.et_name);
		etPhone = (EditText) findViewById(id.et_phone);
		etMail = (EditText) findViewById(id.et_mail);
		actvMailType = (AutoCompleteTextView) findViewById(id.auto_text_email_type);
		tvJob = (TextView) findViewById(id.tv_job);
		tvInvestment = (TextView) findViewById(id.tv_investment);
		etAge = (EditText) findViewById(id.et_age);
		rbtnMale = (RadioButton) findViewById(id.rbtn_male);
		rbtnFemale = (RadioButton) findViewById(id.rbtn_female);
		etAddress = (EditText) findViewById(id.et_address);
		tvClassify = (TextView) findViewById(id.tv_classify);
		tvFollow = (TextView) findViewById(id.tv_follow);
		tvBelong = (TextView) findViewById(id.tv_belong);
		tvRecord = (TextView) findViewById(id.tv_record);
		tvRecourse = (TextView) findViewById(id.tv_recourse);
		tvRemark = (TextView) findViewById(id.tv_remark);
		imgbtnHome = (ImageButton) findViewById(id.imgbtn_home);
		imgbtnHome.setVisibility(View.VISIBLE);
		igmBtnSave = (ImageButton) findViewById(id.imgbtn_save);
		igmBtnSave.setImageDrawable(getResources().getDrawable(
				R.drawable.btn_customer_save_selector));
		igmBtnSave.setVisibility(View.VISIBLE);

		imgbtnSendMsg = (ImageButton) findViewById(id.imgbtn_send_msg);
		imgbtnCallPhone = (ImageButton) findViewById(id.imgbtn_cell_phone);

	}

	private void initDatas() {
		setTitle(getResources().getString(string.customer_title_edit));

		jobStrings = new ArrayList<String>(Arrays.asList(getResources()
				.getStringArray(R.array.customer_jobs)));
		recourseStrings = new ArrayList<String>(Arrays.asList(getResources()
				.getStringArray(R.array.customer_recourse)));
		av = new ArrayAdapter<String>(this, layout.auto_complete_style,
				getResources().getStringArray(R.array.mail_type));

		mCustomerQuery = (CustomerQuery) getIntent().getSerializableExtra(
				ComConst.CUSTOMER_DATAS);
		if (mCustomerQuery == null) {
			mCustomerDetail = new CustomerDetail();
		} else {
			mActivityStatus = 1;
			mCustomerDetail = mCustomerQuery.CustomerDetail;
			displayData();
		}
	}

	private void setOnAllListeners() {
		tvClassify.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(),
						CustomerClassify.class);
				intent.putExtra(ComConst.CUSTOMER_ACTIVITY_STATUS,
						mActivityStatus);
				intent.putExtra(ComConst.CUSTOMER_DATAS, mCustomerDetail);
				startActivityForResult(intent, ComConst.CUSTOMER_CLASSIFY);
				slideNewActivity();
			}
		});

		tvJob.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				int index = 0;
				if (mCustomerDetail.CustomerTrade != null) {
					index = Integer.valueOf(mCustomerDetail.CustomerTrade);
				}

				AlertDialog.Builder builder = new AlertDialog.Builder(
						CustomerEditActivity.this).setTitle(
						getResources().getString(string.customer_job_hint))
						.setSingleChoiceItems(array.customer_jobs, index - 1,
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										mCustomerDetail.CustomerTrade = String
												.valueOf(which + 1);
										tvJob.setText(jobStrings.get(which));
										dialog.dismiss();
									}
								});
				builder.show();
			}
		});

		// AutoCompleteTextView格式绑定
		actvMailType.setAdapter(av);

		tvInvestment.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(),
						CustomerInvestment.class);
				intent.putExtra(ComConst.CUSTOMER_DATAS, mCustomerDetail);
				startActivityForResult(intent, ComConst.CUSTOMER_INVESTMENT);
				slideNewActivity();
			}
		});

		tvFollow.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(),
						CustomerFollow.class);
				intent.putExtra(ComConst.CUSTOMER_FOLLOW_TIME, tvFollow
						.getText().toString());
				startActivityForResult(intent, ComConst.CUSTOMER_FOLLOW);
				slideNewActivity();
			}
		});

		tvRecourse.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				int index = 0;
				if (mCustomerDetail.CustomerFrom != null) {
					index = Integer.valueOf(mCustomerDetail.CustomerFrom);
				}
				AlertDialog.Builder builder = new AlertDialog.Builder(
						CustomerEditActivity.this)
						.setTitle(
								getResources().getString(
										string.customer_recourse_hint))
						.setSingleChoiceItems(array.customer_recourse,
								index - 1,
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										mCustomerDetail.CustomerFrom = String
												.valueOf(which + 1);
										tvRecourse.setText(recourseStrings
												.get(which));
										dialog.dismiss();
									}
								});
				builder.show();
			}
		});

		tvRemark.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Context mContext = CustomerEditActivity.this;
				LayoutInflater inflater = (LayoutInflater) mContext
						.getSystemService(LAYOUT_INFLATER_SERVICE);
				View layout = inflater.inflate(R.layout.dialog_view, null);
				final EditText etDialogRemark = (EditText) layout
						.findViewById(id.et_remark);

				AlertDialog.Builder builder = new AlertDialog.Builder(
						CustomerEditActivity.this);
				builder.setTitle("备注")
						.setView(layout)
						.setPositiveButton("确定",
								new AlertDialog.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										tvRemark.setText(etDialogRemark
												.getText().toString());
										dialog.dismiss();

									}

								})
						.setNegativeButton("取消",
								new AlertDialog.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.dismiss();
									}

								});
				builder.show();
			}
		});

		imgbtnHome.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// getDatas();
				finish();
				slideReturnActivity();
			}
		});

		// if (mCustomerQuery != null && mCustomerQuery.Tag.equals("4"))
		// if (mCustomerQuery != null) {
		// 如果客户信息没通过审核，则没法添加归属信息
		tvRecord.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!("").equals(mCustomerDetail.CustomerID)) {
					Intent intent = new Intent(getApplicationContext(),
							CustomerBelong.class);
					intent.putExtra(ComConst.CUSTOMER_ID,
							mCustomerDetail.CustomerID);
					intent.putExtra(ComConst.CUSTOMER_BELONG_TYPE, "Add");
					startActivityForResult(intent, ComConst.CUSTOMER_BELONG);
					slideNewActivity();
				}

			}
		});

		tvBelong.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(),
						CustomerBelong.class);
				intent.putExtra(ComConst.CUSTOMER_ID,
						mCustomerDetail.CustomerID);
				intent.putExtra(ComConst.CUSTOMER_BELONG_TYPE, "Query");
				startActivity(intent);
				slideNewActivity();
			}
		});

		igmBtnSave.setOnClickListener(saveClickListener);
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (resultCode) {
			case ComConst.CUSTOMER_INVESTMENT :
				// 投资页面返回的信息
				CustomerDetail customerInvestment = (CustomerDetail) data
						.getSerializableExtra(ComConst.CUSTOMER_DATAS);
				mCustomerDetail.CustomerInvestHouseTao = customerInvestment.CustomerInvestHouseTao;
				mCustomerDetail.CustomerInvestHousePing = customerInvestment.CustomerInvestHousePing;
				mCustomerDetail.CustomerInvestHouseType = customerInvestment.CustomerInvestHouseType;
				mCustomerDetail.CustomerInvestShopTao = customerInvestment.CustomerInvestShopTao;
				mCustomerDetail.CustomerInvestShopTotal = customerInvestment.CustomerInvestShopTotal;
				mCustomerDetail.CustomerInvestShopType = customerInvestment.CustomerInvestShopType;
				mCustomerDetail.CustomerInvestStock = customerInvestment.CustomerInvestStock;
				mCustomerDetail.CustomerInvestFund = customerInvestment.CustomerInvestFund;
				tvInvestment.setText(createInvestmentString(mCustomerDetail));
				break;
			case ComConst.CUSTOMER_FOLLOW :
				// 跟进页面返回的信息
				String followTime = data.getStringExtra(
						ComConst.CUSTOMER_FOLLOW_TIME).toString();
				tvFollow.setText(followTime);
				if (followTime != null && !("").equals(followTime)) {
					try {
						mCustomerDetail.CustomerNextTime = dateFormat
								.parse(followTime);
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}
				break;
			case ComConst.CUSTOMER_CLASSIFY :
				// 分类页面返回信息
				CustomerDetail customerClassify = (CustomerDetail) data
						.getSerializableExtra(ComConst.CUSTOMER_DATAS);
				if (customerClassify.CustomerType != null
						&& !("").equals(customerClassify.CustomerType)) {
					tvClassify.setText(getResources().getStringArray(
							array.customer_classify)[Integer
							.valueOf(customerClassify.CustomerType) - 1]);
				}
				mCustomerDetail.CustomerType = customerClassify.CustomerType;
				mCustomerDetail.CustomerTypeTime1 = customerClassify.CustomerTypeTime1;
				mCustomerDetail.CustomerTypeTime2 = customerClassify.CustomerTypeTime2;
				break;
			case ComConst.CUSTOMER_BELONG :
				// 归属页面返回信息
				boolean result = data.getBooleanExtra(
						ComConst.CUSTOMER_BELONG_FLAG, false);
				if (result) {
					tvRecord.setText("已添加沟通记录成功");
				}
				break;
			default :
				break;
		}
	}

	/**
	 * 保存按钮事件、客户信息在这里赋值
	 */
	private View.OnClickListener saveClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			if ((mCustomerQuery == null)
					|| (mCustomerQuery != null && mCustomerQuery.Tag
							.equals("4"))) {
				// mCustomerQuery == null 为新增状态
				// (mCustomerQuery != null && mCustomerQuery.Tag.equals("4"))
				// 为编辑状态
				if (etName.getText().toString().trim().equals("")) {
					Toast.makeText(getApplicationContext(), "客户姓名不能为空",
							Toast.LENGTH_SHORT).show();
					etName.requestFocus();
					return;
				}
				if (etPhone.getText().toString().trim().equals("")) {
					Toast.makeText(getApplicationContext(), "客户电话不能为空",
							Toast.LENGTH_SHORT).show();
					etName.requestFocus();
					return;
				}

				if (mCustomerDetail.CustomerTrade == null
						|| ("").equals(mCustomerDetail.CustomerTrade)) {
					Toast.makeText(getApplicationContext(), "客户职业不能为空",
							Toast.LENGTH_SHORT).show();
					tvJob.requestFocus();
					return;
				}

				if (mCustomerDetail.CustomerFrom == null
						|| ("").equals(mCustomerDetail.CustomerFrom)) {
					Toast.makeText(getApplicationContext(), "客户来源不能为空",
							Toast.LENGTH_SHORT).show();
					tvRecourse.requestFocus();
					return;
				}

				if (mCustomerDetail.CustomerType == null
						|| ("").equals(mCustomerDetail.CustomerType)) {
					Toast.makeText(getApplicationContext(), "客户分类不能为空",
							Toast.LENGTH_SHORT).show();
					tvClassify.requestFocus();
					return;
				}

				mCustomerDetail.CustomerName = etName.getText().toString();
				mCustomerDetail.CustomerPhone = etPhone.getText().toString();
				if (!etMail.getText().toString().trim().equals("")
						|| !actvMailType.getText().toString().trim().equals("")) {
					mCustomerDetail.CustomerMail = etMail.getText() + "@"
							+ actvMailType.getText().toString();
				}

				if (!etAge.getText().toString().equals("")) {
					mCustomerDetail.CustomerAge = Integer.valueOf(etAge
							.getText().toString());
				}

				if (rbtnMale.isChecked()) {
					mCustomerDetail.CustomerGender = "1";
				} else {
					mCustomerDetail.CustomerGender = "0";
				}

				mCustomerDetail.CustomerAddress = etAddress.getText()
						.toString();

				mCustomerDetail.CustomerMemo = tvRemark.getText().toString()
						.trim();
				mCustomerDetail.UserNum = User.getInstance(
						getApplicationContext()).getUserNum();

				try {
					SaveCustomerInfo saveCustomerInfo = new SaveCustomerInfo();
					saveCustomerInfo.execute(mCustomerDetail);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				Toast.makeText(getApplicationContext(), "客户信息尚未通过审核，您无权限修改",
						Toast.LENGTH_SHORT).show();
			}

		}
	};

	/**
	 * 获取信息
	 * 
	 * @author hby
	 * 
	 */
	private class SaveCustomerInfo extends AsyncTask<Object, Object, String> {
		private ProgressDialog pd;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			try {
				pd = new ProgressDialog(CustomerEditActivity.this);
				pd.setMessage("查询中...");
				pd.setIndeterminate(false);
				pd.setCancelable(false);
				pd.show();
			} catch (Exception e) {
				Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
			}
		}

		@Override
		protected String doInBackground(Object... arg0) {
			String result = "";
			try {
				if (null != arg0 && arg0.length > 0) {
					result = CustomerServiceProxy.getInstance(
							CustomerEditActivity.this).CustomerCreate(
							(CustomerDetail) arg0[0]);
				}
			} catch (Exception e) {
				Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			pd.cancel();
			if (result.equals("success")) {
				Toast.makeText(CustomerEditActivity.this,
						R.string.customer_save_success, Toast.LENGTH_LONG)
						.show();
				imgbtnHome.performClick();
				return;
			} else if (result.equals("failed")) {
				Toast.makeText(CustomerEditActivity.this,
						R.string.customer_save_failed, Toast.LENGTH_LONG)
						.show();
			} else if (result.equals("has")) {
				Toast.makeText(CustomerEditActivity.this,
						R.string.customer_save_has, Toast.LENGTH_LONG).show();
			} else if (result.equals("error")) {
				Toast.makeText(CustomerEditActivity.this,
						R.string.customer_save_error, Toast.LENGTH_LONG).show();
			}
		}
	}

	private void displayData() {
		etName.setText(mCustomerDetail.CustomerName);
		etPhone.setText(mCustomerDetail.CustomerPhone);
		if (mCustomerQuery.Tag.equals("4")) {
			imgbtnSendMsg.setVisibility(View.VISIBLE);
		} else {
			imgbtnSendMsg.setVisibility(View.VISIBLE);
		}

		if (mCustomerDetail.CustomerMail != null
				&& !("").equals(mCustomerDetail.CustomerMail)) {
			String[] email = mCustomerDetail.CustomerMail.split("@");
			if (email.length > 1) {
				etMail.setText(email[0]);
				actvMailType.setText(email[1]);
			}
		}

		tvJob.setText(getResources().getStringArray(array.customer_jobs)[Integer
				.valueOf(mCustomerDetail.CustomerTrade) - 1]);
		tvInvestment.setText(createInvestmentString(mCustomerDetail));
		etAge.setText(String.valueOf(mCustomerDetail.CustomerAge));
		if (mCustomerDetail.CustomerGender.equals("1")) {
			rbtnMale.setChecked(true);
		} else {
			rbtnFemale.setChecked(true);
		}
		etAddress.setText(mCustomerDetail.CustomerAddress);
		tvClassify.setText(getResources().getStringArray(
				array.customer_classify)[Integer
				.valueOf(mCustomerDetail.CustomerType) - 1]);
		if (mCustomerDetail.CustomerNextTime != null
				&& !("").equals(mCustomerDetail.CustomerNextTime)) {
			tvFollow.setText(dateFormat
					.format(mCustomerDetail.CustomerNextTime));
		}
		tvRecourse.setText(getResources().getStringArray(
				array.customer_recourse)[Integer
				.valueOf(mCustomerDetail.CustomerFrom) - 1]);
		if (mCustomerDetail.CustomerMemo != null) {
			tvRemark.setText(mCustomerDetail.CustomerMemo);
		}
	}

	private String createInvestmentString(CustomerDetail customerDetail) {
		StringBuilder investStringBuilder = new StringBuilder();
		investStringBuilder.append("已投资");
		if (mCustomerDetail.CustomerInvestHouseTao != null
				&& !mCustomerDetail.CustomerInvestHouseTao.equals("")) {
			investStringBuilder.append("住宅、");
		}
		if (mCustomerDetail.CustomerInvestShopTao != null
				&& !mCustomerDetail.CustomerInvestShopTao.equals("")) {
			investStringBuilder.append("商铺、");
		}
		if (mCustomerDetail.CustomerInvestStock.equals("1")) {
			investStringBuilder.append("股票、");
		}
		if (mCustomerDetail.CustomerInvestFund.equals("1")) {
			investStringBuilder.append("基金、");
		}
		if (investStringBuilder.length() > 3) {
			investStringBuilder.replace(investStringBuilder.length() - 1,
					investStringBuilder.length(), "");
		} else {
			investStringBuilder.replace(0, investStringBuilder.length(),
					"无任何投资");
		}
		return investStringBuilder.toString();
	}

	/**
	 * 获取第一个通话记录（必须是通话成功，有通话时间的）
	 * 
	 * @return
	 */
	private CallLog getFirstCallLog() {
		CallLog callLog = null;
		Cursor cursor = null;
		try {

			/**
			 * sleep(150),通话结束状态
			 */
			Thread.sleep(150);
			/**
			 * type = 2:表示通话拨出 date desc limit 1：表最新一条通话记录
			 */
			cursor = getContentResolver()
					.query(android.provider.CallLog.Calls.CONTENT_URI,
							null,
							"number=" + mCustomerDetail.CustomerPhone
									+ " and type = 2", null,
							"date desc limit 1");

			if (cursor.moveToFirst()) {
				Date date = new Date(Long.parseLong(cursor.getString(cursor
						.getColumnIndexOrThrow(Calls.DATE))));
				String number = cursor.getString(cursor
						.getColumnIndex(Calls.NUMBER));

				// 通话时间,单位:s
				int duration = Integer.valueOf(cursor.getString(cursor
						.getColumnIndexOrThrow(Calls.DURATION)));
				// 通话时间必须大于0,
				if (mCustomerDetail.CustomerPhone.equals(number)
						&& duration > 0) {
					// 呼叫时间
					if (callLog == null) {
						callLog = new CallLog();
						callLog.CallSeconds = duration;
						callLog.CustomerID = mCustomerDetail.CustomerID;
						callLog.CallTime = date;
						callLog.UserNum = User.getInstance(
								getApplicationContext()).getUserNum();
					}
				}
			}

		} catch (Exception e) {
			Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
		} finally {
			cursor.close();
		}

		return callLog;
	}

	/**
	 * 通话记录上传异步类
	 * 
	 * @author MyPC
	 * 
	 */
	private class saveCallLogTask extends AsyncTask<Object, Object, Integer> {
		private ProgressDialog pd;
		@Override
		protected Integer doInBackground(Object... params) {
			int result = -1;
			try {
				if (params != null && params.length > 0) {
					result = CustomerServiceProxy.getInstance(
							getApplicationContext()).CallLogCreate(
							(CallLog) params[0]);
				}
			} catch (Exception e) {
				Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
			}
			return result;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			try {
				pd = new ProgressDialog(CustomerEditActivity.this);
				pd.setMessage("发送中...");
				pd.setIndeterminate(false);
				pd.setCancelable(false);
				pd.show();
			} catch (Exception e) {
				Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
			}
		}

		@Override
		protected void onPostExecute(Integer result) {
			pd.cancel();
			if (result == 1) {
				Toast.makeText(CustomerEditActivity.this, "通话记录上传成功",
						Toast.LENGTH_LONG).show();
			}
			super.onPostExecute(result);
		}

	}
}
